JavaScript sorting
There are times, though,
when we either don't want to wait for server responses when sorting, or
don't have a server-side scripting language available to us. A viable
alternative in this case is to perform the sorting entirely on the
browser using JavaScript client-side scripting.
For example, suppose we have a table listing books, the author names, release dates, and prices:
<table class="sortable">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Author(s)</th>
<th>Publish Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="../images/covers/small/1847192386.png"
width="49" height="61" alt="Building Websites with
Joomla! 1.5 Beta 1" />
</td>
<td>Building Websites with Joomla! 1.5 Beta 1</td>
<td>Hagen Graf</td>
<td>Feb 2007</td>
<td>$40.49</td>
</tr>
<tr>
JavaScript sorting, sortingexample<td><img src="../images/covers/small/1904811620.png"
width="49" height="61" alt="Learning Mambo: A
Step-by-Step Tutorial to Building Your Website" />
</td>
<td>Learning Mambo: A Step-by-Step Tutorial to Building
Your Website
</td>
<td>Douglas Paterson</td>
<td>Dec 2006</td>
<td>$40.49</td>
</tr>
</tbody>
</table>
We'd like to turn the table
headers into buttons that sort the data by their respective columns.
Let's explore some ways of doing this.
Row grouping tags
Note our use of the<thead> and<tbody> tags to segment the data into row groupings.
Many HTML authors omit these implied tags, but they can prove useful in
supplying us with more convenient CSS selectors to use. For example,
suppose we wish to apply typical even/odd row striping to this table,
but only to the body of the table:
$(document).ready(function() {
$('table.sortable tbody tr:odd').addClass('odd');
$('table.sortable tbody tr:even').addClass('even');
});
This will add alternating colors to the table, but leave the header untouched:
Using these row grouping tags, we will be able to easily select and manipulate the data rows without affecting the header.